Public Class frmProject
    Inherits System.Windows.Forms.Form

    Private Sub frmProject_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        LoadForm()
    End Sub

    Private Sub LoadForm()
        Try
            With lvwProjects
                .Items.Clear()
                For Each kv As Generic.KeyValuePair(Of String, String) In clsConnections.GetProjectList

                    If False Then
                        'following could be used to test to make sure that the current user has permissions on the database before adding it to the list
                        'it somewhat slows down the display of the projects though

                        Dim p As New clsProject(kv.Key, True)
                        clsConnections.GetProjectInfo(p) 'will instantiate
                        If p IsNot Nothing AndAlso p.DB IsNot Nothing AndAlso p.DB.TestConnectionQuick(1) Then
                            Dim lvitem As New ListViewItem(kv.Key)
                            lvitem.SubItems.Add(kv.Value & IIf(kv.Key = Project.Name, " [Active Project]", ""))
                            .Items.Add(lvitem)
                        End If
                    Else
                        'following is original code

                        Dim lvitem As New ListViewItem(kv.Key)
                        lvitem.SubItems.Add(kv.Value & IIf(Project IsNot Nothing AndAlso kv.Key = Project.Name, " [Active Project]", ""))
                        .Items.Add(lvitem)
                    End If
 
                Next
                .Columns(0).Width = -1
                .Columns(1).Width = -2
                For i As Integer = 0 To .Items.Count - 1
                    If .Items(i).SubItems(0).Text = clsApplicationSettings.GetKey(enumKey.LastProjectName, "") Then
                        .Items(i).Selected = True
                        .FocusedItem = .Items(i)
                        .EnsureVisible(i)
                    End If
                Next
                .Focus()
            End With
            Me.Text &= $" - {clsApplicationSettings.WorkspaceName} ({clsProject.ReplaceMyDocs(clsApplicationSettings.AppDataPath)})"
            ToolTip1.SetToolTip(btnConfig, "Current WRDB Project configuration directory: " & clsProject.ReplaceMyDocs(clsApplicationSettings.AppDataPath))
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub lvwProjects_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvwProjects.DoubleClick
        Me.btnOpen.PerformClick()
    End Sub

    Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
        'don't need to be supervisor to create new project, or could get stuck if only a single protected project
        'If Not SupervisorEnabled() Then Exit Sub
        If MainForm.FileNewProject() Then Close()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        Try
            If Not SupervisorEnabled() Then Exit Sub
            If lvwProjects.SelectedItems.Count = 0 Then Exit Sub
            'SetProject(lvwProjects.SelectedItems(0).Text)
            Project = New clsProject(lvwProjects.SelectedItems(0).Text)
            With New frmPrefs
                .ShowDialog()
                .Dispose()
            End With
            LoadForm()
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub btnRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRename.Click
        Try
            If Not SupervisorEnabled() Then Exit Sub
            If lvwProjects.SelectedItems.Count = 0 Then Exit Sub
            Dim OldName As String = Me.lvwProjects.SelectedItems(0).Text
            Dim NewName As String = InputBox("Enter the new name for this project:", "Rename Project", OldName).Trim
            If NewName = "" Then Exit Sub
            If clsConnections.RenameProject(OldName, NewName) Then
                SetProject(NewName)
                LoadForm()
            Else
                ErrorMsg(String.Format("Unable to rename project {0} to {1}; the new project name may already exist.", OldName, NewName))
            End If
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Try
            If Not SupervisorEnabled() Then Exit Sub
            If lvwProjects.SelectedItems.Count = 0 Then Exit Sub
            Dim ProjectName As String = Me.lvwProjects.SelectedItems(0).Text
            If Project IsNot Nothing AndAlso ProjectName.ToUpper = Project.Name.ToUpper Then
                WarningMsg("You cannot delete the currently active project; please select a different project first.")
                LoadForm()
                Exit Sub
            End If
            Try
                Dim prj As New clsProject(ProjectName)
                With prj.DB
                    .CloseConnection()
                    clsConnections.GetProjectInfo(prj)
                    Select Case MessageBox.Show(StringFormat("This will remove the selected project specification from the WRDB configuration file so that it will no longer show up in this project list. In a moment you will also be prompted to optionally delete any tables and/or database files that are referenced by this project.\n\nDo you want to proceed?"), "Delete Project", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
                        Case Windows.Forms.DialogResult.OK
                            Select Case .DatabaseType
                                Case clsDB.enumDBType.Access, clsDB.enumDBType.Firebird_Embedded, clsDB.enumDBType.SQLite, clsDB.enumDBType.SQL_Server_CE
                                    If WarningMsgFmt("Do you want to delete the database file ({0}), thus PERMANENTLY DELETING ALL DATA AND SUPPORT TABLES associated with this project?", .DataSource.Replace("\", "\\")) = Windows.Forms.DialogResult.OK Then
                                        If My.Computer.FileSystem.FileExists(.DataSource) Then My.Computer.FileSystem.DeleteFile(.DataSource, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.SendToRecycleBin)
                                    End If
                                Case clsDB.enumDBType.Firebird, clsDB.enumDBType.MySQL, clsDB.enumDBType.Oracle, clsDB.enumDBType.SQL_Server
                                    Try
                                        Dim ThisProject As clsProject = Nothing
                                        'try to connect so can delete tables; if fails, just remove project
                                        If .TestConnectionQuick(CONNECTIONTIMEOUT) Then
                                            Dim lst As Generic.List(Of String) = prj.GetTableListAll
                                            If WarningMsgFmt("Do you want to PERMANENTLY DELETE ALL {0} DATA AND SUPPORT TABLES IN THE SERVER DATABASE ({1}) associated with this project (the database itself must be removed by a database administrator)?", lst.Count, .DataSource) = Windows.Forms.DialogResult.OK Then
                                                For Each tbl As String In lst
                                                    .DropTable(tbl)
                                                Next
                                            End If
                                        End If
                                        .Dispose()
                                    Catch ex As Exception
                                    End Try
                            End Select
                        Case Windows.Forms.DialogResult.Cancel
                            Exit Sub
                    End Select
                End With
            Catch ex As Exception
                WarningMsg("Unable to connect to project; removing from list anyway.")
            End Try
            RemoveProject(ProjectName)
            LoadForm()
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub RemoveProject(ByVal ProjectName As String)
        Try
            If Not clsConnections.DeleteProject(ProjectName) Then Exit Sub
            If Project IsNot Nothing AndAlso ProjectName = Project.Name Then
                If clsConnections.GetProjectList.Count = 0 Then
                    clsApplicationSettings.SetKey(enumKey.LastProjectName, "")
                Else
                    clsApplicationSettings.SetKey(enumKey.LastProjectName, clsConnections.GetProjectList(0))
                End If
            End If
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub btnConfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfig.Click
        Try
            'Browse to WRDB6.ini file (so could paste the full path in)
            With New OpenFileDialog
                .AutoUpgradeEnabled = True
                .CheckFileExists = False
                .CheckPathExists = True
                .FileName = "WRDB6.ini"
                .Filter = "WRDB 6 configuration file|WRDB6.ini"
                .InitialDirectory = clsApplicationSettings.AppDataPath
                .Multiselect = False
                .Title = "Browse to select WRDB configuration file that will define the Project Workspace:"
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    If Not My.Computer.FileSystem.FileExists(.FileName) Then
                        If WarningMsg("A WRDB configuration file was not found in the folder you selected. Do you want to create a new empty file?") = Windows.Forms.DialogResult.Cancel Then Exit Sub
                    End If
                    clsApplicationSettings.AppDataPath = IO.Path.GetDirectoryName(.FileName)
                    MainWRDB = New WRDB.Lib.clsWRDB
                End If
                .Dispose()
            End With
            LoadForm()
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub
End Class
